/*
 * @Author: yangzonglong
 * @Date: 2020-06-30 13:21:05
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-17 09:46:19
 * @Auditor:
 */
import { ISelected, FormxChange, SelectChange } from './interface';
import { setExtra } from './../../components/formx/util';
import { parse } from './../../utils/json/json';
import { parsingStr } from './../../utils/replace/replace';
interface HandleChangeOptions {
  value: string | string[];
  id: undefined | string;
  dataSource: any[];
  fieldNames: ISelected;
  extra?: string[];
  onChange?: FormxChange | SelectChange;
}

function selectItemsMapInValue(dataSource: any[], fieldNames: ISelected) {
  return dataSource.reduce((next, cur) => {
    next[cur[fieldNames.value]] = cur;
    return next;
  }, {});
}

function handleMultipleChange({ dataSource, value, fieldNames, onChange, id }: HandleChangeOptions) {

  const items = (value as string[])?.map((item) => dataSource.filter((ele) => ele[fieldNames.value] === item)?.[0]);

  const dataSourceMapInValue = selectItemsMapInValue(dataSource, fieldNames);

  const selects = items.map((item: any) => {

    const curData = dataSourceMapInValue[item?.[fieldNames.value]] || {};
    return {
      label: curData[fieldNames.label],
      value: curData[fieldNames.value],
    };
  });

  if (!id) return (onChange as SelectChange)?.(selects, items);

  setExtra({ ['_' + id]: items });
  return (onChange as FormxChange)(value, id);
}

function handleRadioChange({ dataSource, fieldNames, value, extra, id, onChange }: HandleChangeOptions) {
  const item = dataSource.find((item) => evalJsStr(item, fieldNames.value) === value),
    extraValue = {},
    _extra = typeof extra === 'string' ? parse(extra) : extra;

  if (_extra && _extra.length) {
    _extra.forEach((extraItem: any) => {
      if (extraItem.indexOf(':') > 0) {
        const arr = extraItem.split(':');
        extraValue[arr[1]] = evalJsStr(item, arr[0]);
      } else {
        extraValue[extraItem] = evalJsStr(item, extraItem);
      }
    });
  }

  if (!id) return (onChange as SelectChange)?.({ label: evalJsStr(item, fieldNames.label), value: value as any }, item!);

  setExtra(extraValue);
  (onChange as FormxChange)?.(value, id!);
}

export function handleChange(options: HandleChangeOptions) {
  if (Array.isArray(options.value)) return handleMultipleChange(options);
  handleRadioChange(options);
}

export function handleValue(value: undefined | string | number | string[], mode?: string) {
  if (!value) return mode ? [] : !!value ? value : undefined;
  return !!value ? value : undefined;
}

export function evalJsStr(data: object, jsStr: string) {
  data = data || {};
  if (jsStr.includes('{{')) return parsingStr(jsStr, data).replace(/"/g, '');
  if (!jsStr.includes('.')) return data[jsStr];

  (window as any)._selectEvalJsData = data;
  const val = eval(`_selectEvalJsData.${jsStr}`);
  return val;
}

export function setInitExtra(key: string, value: string | string[], data: Object[], fieldNames: ISelected) {
  setExtra({
    ['_' + key]: data.filter((item) => {
      if (Array.isArray(value)) return value.includes(item[fieldNames.value]);
      return item[fieldNames.value] === value;
    }),
  });
}
